import * as echarts from '../ec-canvas/echarts';

let Chart = null
let maxCountElement = 0
let recentVoltage = []
let N = 40
let diff = 0.002
let length = 100

Page({
  data: {
    ec: {
      lazyLoad: true // 延迟加载
    },
    connectStatus: "连接设备",
    chs: [],
    connected: false,
    showDeviceList: false,
    result: "无",
    devices: [],
    names: [],
    times: [],
    voltage: [],
    pressure: [],
    realTimeVoltage: 0,
    realTimePressure: 0
  },

  onLoad: function () {
    this.echartsComponnet = this.selectComponent('#chart_line')
    this.init_echarts()
    let that = this

  },
  toggle(type) {
    this.setData({
      [type]: !this.data[type],
    });
  },
  onSelect(e) {
    let device = e.detail
    let devices = this.data.devices
    this.createBLEConnection(device)
  },

  //识别第一个字符将剩余字符转为十进制数字
  getData(data) {
    let voltage = (Number(data) - 787) * 0.00015
    if (voltage < 0){
      voltage = 0
    }
    let pressure = Number(this.get_pressure(voltage))
    let that = this
    if (recentVoltage.length >= N)
      recentVoltage.shift()
    recentVoltage.push(voltage)
    maxCountElement = this.get_maxCount_element(recentVoltage)
    console.log(maxCountElement);
    if (Math.abs(voltage - maxCountElement) < diff) {
      voltage = maxCountElement
      pressure = Number(this.get_pressure(voltage))
    }
    if(this.data.voltage.length > length){
      this.data.voltage.shift()
      this.data.pressure.shift()
    }
    this.data.voltage.push(voltage)
    this.data.realTimeVoltage = String(voltage)
    this.data.realTimePressure = String(pressure.toFixed(3))
    this.data.pressure.push(pressure)
    this.setData(that.data)
  },
  get_pressure(voltage) {
    return voltage
  },




  Connect() {
    if (!this.data.connected) {
      this.toggle('showDeviceList')
      wx.openBluetoothAdapter({
        success: (res) => {
          console.log('openBluetoothAdapter success', res)
          this.startBluetoothDevicesDiscovery()
        },
        fail: (res) => {
          if (res.errCode === 10001) {
            wx.onBluetoothAdapterStateChange(function (res) {
              console.log('onBluetoothAdapterStateChange', res)
              if (res.available) {
                this.startBluetoothDevicesDiscovery()
              }
            })
          }
        }
      })
    } else {
      this.closeBLEConnection()
    }
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
          data[`devices[${idx}]`].id = idx
          data[`devices[${idx}]`].subname = 'UUID: ' + device.deviceId
          this.setData(data)
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(device) {
    // const ds = e.currentTarget.dataset
    const deviceId = device.deviceId
    const name = device.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        // setInterval(() => {
        //   this.pushTime()          
        // }, 2000);
        this.setData({
          connected: true,
          connectStatus: "断开连接",
          name,
          deviceId,
        })
        wx.showToast({
            title: '连接成功',
            icon: 'success'
          }),
          this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
      connectStatus: "连接设备"
    })
    wx.showToast({
      title: '已断开',
      duration: 1000,
      icon: "success"
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  toRealValue(number) {
    let digit = []
    if (number == NaN)
      return 0
    while (number != 0) {
      digit.push(number % 10)
      number = Math.floor(number / 10)
    }
    let result = 0
    while (digit.length > 1) {
      result = (digit.pop() + result) * 16
    }
    result = result + digit.pop()
    return result
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    let that = this
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              success: function (res) {
                wx.onBLECharacteristicValueChange(res => {
                  let result = Number(that.toRealValue(ab2dec(res.value))).toString()
                  if (result.length <= 4) {
                    console.log(result);
                    that.getData(result)
                    // console.log(that.data.voltage);
                    Chart.setOption(that.getOption())
                  }
                })
              }
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
  },
  writeBLECharacteristicValue(num) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, num)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },


  init_echarts: function () {
    this.echartsComponnet.init((canvas, width, height, dpr) => {
      // 初始化图表
      Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      Chart.setOption(this.getOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },
  get_maxCount_element: function (arr) {
    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      let key = arr[i];
      if (obj[key]) {
        obj[key]++;
      } else {
        obj[key] = 1;
      }
    }

    let maxCount = 0;
    let maxElement = arr[0];
    for (let key in obj) {
      if (maxCount < obj[key]) {
        maxCount = obj[key];
        maxElement = key;
      }
    }
    return maxElement
    // return "该数组中出现次数最多的元素:"+maxElement+"出现了"+maxCount+"次";  
  },
  getOption: function () {
    // 指定图表的配置项和数据
    let option = {
      title: {
        text: '压力曲线',
        left: 'left',
        top: 18,
        left: 10
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['压力', '电压'],
        show: true,
        z: 999,
        right: 15,
        top: 20,

      },
      xAxis: [{
        type: 'value',
        min: 0,
        max: 10,
        nameLocation: 'center',
        nameTextStyle: {
          lineHeight: 30,
        },
        axisLine: {
          show: true
        },
        name: 'T/s',
        nameLocation: 'end'
      }, {
        type: 'category',
      }],
      yAxis: [{
        type: 'value',
        scale: true,
        min: 0,
        max: 0.8,
        position: 'left'
      }, {
        type: 'category',
      }],
      series: [{
        name: '压力',
        type: 'line',
        id: 0,
        barWidth: '60%',
        animation: false,
        xAxisIndex: 1,
        yAxisIndex: 0,
        symbol: 'none', //取消折点圆圈
        smooth: true,
        data: this.data.voltage
      }
      // , {
      //   name: '电压',
      //   type: 'line',
      //   id: 1,
      //   barWidth: '60%',
      //   animation: false,
      //   xAxisIndex: 1,
      //   yAxisIndex: 0,
      //   symbol: 'none', //取消折点圆圈
      //   smooth: true,
      //   // data: this.data.voltage
      // }
    ],
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        }
      }
    }
    return option;
  },
});



function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进制字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

// ArrayBuffer转10进制字符串示例
function ab2dec(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(10)).slice(-2)
    }
  )
  return hexArr.join('');
}